package codeTop;

import java.util.Arrays;

public class q16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - 2; i++) {
            int num = target-nums[i];
            int r = nums.length-1;
            for (int l = i+1; l < nums.length - 1; l++) {
                while (l < r && nums[l] + nums[r] > num) {
                    if (Math.abs(res - target) > Math.abs(nums[l] + nums[r] - num)) {
                        res = nums[i]+nums[l]+nums[r];
                    }
                    r--;
                }
                if (l<r&&Math.abs(res - target) > Math.abs(nums[l] + nums[r] - num)) {
                    res = nums[i]+nums[l]+nums[r];
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        q16 q = new q16();
        System.out.println(q.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
    }
}
